package com.nulldev.util.data.DataTransferAPI;

import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import com.nulldev.util.VariableAPI.MathUtil;
import com.nulldev.util.networking.rudp.util.SerializationUtils;

public class DataTransfer implements Closeable {

	private final InputStream is;

	public DataTransfer(final InputStream is) {
		this.is = is;
	}

	public int readInt() throws IOException {
		byte[] buffer = new byte[4];
		if (is.read(buffer) < 0)
			throw new EOFException();
		return MathUtil.getInt(buffer, 0);
	}

	public long readLong() throws IOException {
		byte[] buffer = new byte[8];
		if (is.read(buffer) < 0)
			throw new EOFException();
		return MathUtil.getLong(buffer, 0);
	}

	public byte[] read(final int size) throws IOException {
		if (size <= 0) {
			throw new NullPointerException("read(int): size <= 0!");
		}
		byte[] buffer = new byte[size];
		if (is.read(buffer) < 0)
			throw new EOFException();
		return buffer;
	}

	public String read() throws IOException {
		final int size = this.readInt();
		return new String(this.read(size));
	}

	public boolean readBoolean() throws IOException {
		return is.read() == 1;
	}

	public <T> T readObject() throws IOException {
		final int size = this.readInt();
		return SerializationUtils.getInstance().deserialize(this.read(size));
	}

	@Override
	public void close() throws IOException {
		this.is.close();
	}
}
